import { login } from "@/api/user"
import storage from "../../utils/storage"

export default {
  namespaced: true,
  state: {
    token: storage.getItem('token'),
    userInfo: storage.getItem("userInfo")
  },
  mutations: {
    SET_TOKEN(state, payload) {
      state.token = payload
    },
    SET_USER_INFO(state, payload) {
      state.userInfo = payload
    }
  },
  actions: {
    login({ commit }, payload) {
      return new Promise((resolve, reject) => {
        login({ username: payload.username.trim(), password: payload.password.trim() })
          .then(res => {
            storage.setItem('token', res.data.message.token)
            storage.setItem("userInfo", res.data.message)
            commit("SET_TOKEN", res.data.message.token)
            commit("SET_USER_INFO", res.data.message)
            resolve()
          })
          .catch((err) => {
            reject(err)
          })
      })
    }
  }
}